import React, { useEffect, useState } from 'react';
import { Button, Cascader, Form, Input, message, Row, Select, Space } from 'antd';
import Login from '../login';
import { useRequest, useUnmount } from 'ahooks';
import * as APIS from '../../../constants/api-constants';
import { GLOBAL_SELECTIONS, TEL_REGISTERED } from '../../../constants/api-constants';
import { LOGIN } from '../index';
import axios from 'axios';
import provice from '../../../util/place';
import md5 from 'md5';

const options = provice;

const { Option } = Select;

interface ShowProps {
  onPageStateChange: (pageState: string) => void;
}

const Registry: React.FC<ShowProps> = (props) => {
  const formLayout = {
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 19,
    },
  };
  const { onPageStateChange } = props;
  const [form] = Form.useForm<Login>();
  const [titleTypeOptions, setTitleTypeOptions] = useState<any>([]);
  const [positionTypeOptions, setPositionTypeOptions] = useState<any>([]);

  let { loading, run, cancel } = useRequest(
    (data) => {
      let { tel, password, username, address, organization, title, position, email } = data;
      return {
        url: APIS.REGISTER,
        method: 'POST',
        data: { tel, password: md5(password), username, address, organization, title, position, email },
      };
    },
    {
      manual: true,
      onSuccess: (result) => {
        const { code } = result.data.mainData;
        if (code === 0) {
          message.success('账号注册成功');
          form.resetFields();
          onPageStateChange(LOGIN);
          return;
        } else {
          message.error('服务器异常，请稍后再试');
          form.resetFields();
        }

      },
      onError: () => {
        message.error('服务器异常，请稍后再试');
        console.log('onError');
      },
    }
  );
  useUnmount(() => {
    cancel();
  });

  useEffect(() => {
    axios
      .get(GLOBAL_SELECTIONS)
      .then(r => {
        const { mainData } = r.data;

        const titleOptions = mainData.titleType.map((item: any) => {
          return (
            <Option key={item.uuid} value={item.uuid}>
              {item.name}
            </Option>
          );
        });

        const positionOptions = mainData.positionType.map((item: any) => {
          return (
            <Option key={item.uuid} value={item.uuid}>
              {item.name}
            </Option>
          );
        });

        setTitleTypeOptions(titleOptions);
        setPositionTypeOptions(positionOptions);
      })
      .catch(e => {
        console.log(e);
      });
  }, []);

  return (
    <div className="index-box">
      <div className="index-inner-box">
        <div className="index-inner-left-box"/>
        <div className="index-inner-middle-box-registry">
          <div>
            <span id="info-span1">欢迎登录</span>
            <span id="info-span2">知识产权综合服务平台</span>
          </div>

          <span id="info-span3">
            Copyright&copy;天津国科医工科技发展有限公司,All Rights Reserved.
          </span>
        </div>
        <div className="index-inner-right-box-registry">
          <span id="password-login-span">注册新用户</span>
          <div className="form-container">
            <Form onFinish={(e) => run(e)} form={form} labelAlign="right" {...formLayout}>
              <Form.Item
                name="tel"
                label="手机号"
                rules={[
                  { message: '手机号不能为空', required: true },
                  { message: '手机格式不正确', pattern: /^[1][3-9][0-9]{9}$/ },
                  {
                    validator: (_, value) => {
                      if (value.length === 11) {
                        return axios.post(TEL_REGISTERED, { tel: value })
                          .then(res => {
                            console.log(value);

                            console.log(res);
                            if (res.data.mainData) {
                              return Promise.reject(new Error('电话号码已被注册'));
                            }
                            return Promise.resolve();
                          });
                      }
                      return Promise.resolve();
                    }

                  },
                ]}
              >
                <Input placeholder="手机号即为登录账号"/>
              </Form.Item>
              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { message: '密码不能为空', required: true },
                  { message: '密码长度必须大于等于6位', min: 6 },
                  { message: '密码长度必须小于等于32位', max: 32 },
                ]}
              >
                <Input
                  placeholder="请输入登录密码"
                  type="password"
                />
              </Form.Item>
              <Form.Item
                name="passwordConfirm"
                label="确认密码"
                rules={[{ message: '请确认你的密码', required: true },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不同'));
                    },
                  })
                ]}
              >
                <Input
                  placeholder="请再次输入登录密码"
                  type="password"
                />
              </Form.Item>
              <Form.Item
                name="username"
                label="用户名"
                rules={[{ message: '用户名不能为空', required: true }]}
              >
                <Input placeholder="请输入用户名"/>
              </Form.Item>
              <Form.Item
                name="email"
                label="e-mail"
                rules={[
                  {
                    type: 'email',
                    message: '邮箱格式不正确!',
                  },
                  {
                    required: true,
                    message: '请输入您的邮箱!',
                  },
                ]}
              >
                <Input placeholder="请输入邮箱"/>
              </Form.Item>
              <Form.Item
                name="address"
                label="地址"
                rules={[{ required: true, message: '地址不能为空' }]}
              >
                <Cascader options={options} placeholder="请选择地址"/>
              </Form.Item>
              <Form.Item
                name="organization"
                label="所属机构"
                rules={[{ message: '所属机构不能为空', required: true }]}
              >
                <Input placeholder="请输入所属机构"/>
              </Form.Item>
              <Form.Item
                label="职称"
                name="title"
                rules={[{ required: true, message: '职称不能为空' }]}
              >
                <Select>{titleTypeOptions}</Select>
              </Form.Item>
              <Form.Item
                label="职务"
                name="position"
                rules={[{ required: true, message: '岗位不能为空' }]}
              >
                <Select>{positionTypeOptions}</Select>
              </Form.Item>
              <Row align="middle" justify="end">
                <Space align="center">
                  <Form.Item>
                    <Button
                      loading={loading}
                      type="primary"
                      size="large"
                      onClick={() => {
                        form.submit();
                      }}
                    >
                      注册
                    </Button>
                  </Form.Item>
                  <Form.Item>
                    <Button
                      loading={loading}
                      size="large"
                      onClick={() => {
                        onPageStateChange(LOGIN);
                      }}
                    >
                      返回登录
                    </Button>
                  </Form.Item>
                </Space>
              </Row>

            </Form>
          </div>

        </div>
      </div>
    </div>
  );
};

export default Registry;
